import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class participa
 */
@WebServlet("/participar")
public class participar extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private Gson gson;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public participar() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		gson = new Gson();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		recivDate(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		recivDate(request, response);
	}

	private void recivDate(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("application/json; charset=UTF-8");
			String idReplyString = request.getParameter("idReply");
			String idUser = request.getParameter("idUser");

			Long idReply = Long.valueOf(idReplyString);

			int votes = 0;

			for (Reply rep : Dades.getQuery(0).getReplies()) {
				if (rep.getId() == idReply) {
					rep.setNumberOfVotes(rep.getNumberOfVotes() + 1);
					rep.setSelected(true);
				} else {
					rep.setSelected(false);
				}
				votes += rep.getNumberOfVotes();
			}
			Dades.getQuery(0).setVotesTotal(votes);
			response.getWriter().println(gson.toJson(Dades.getQuery(0)));
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
